<template>
  <div v-loading="loading" class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="其他入库单号" prop="formCode">
          <CodeRuleInput :band-value.sync="formData.formCode" table-name="wms_other_in_form" column-name="form_code" :is-edit="id" />
        </el-form-item>
        <el-form-item label="入库人员" prop="name">
          <el-input v-model="formData.inByName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="入库时间" prop="purchaseTime">
          <el-date-picker
            v-model="formData.inTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="入库类型" prop="formTypeId">
          <DictSelect
            :band-value.sync="formData.formTypeId"
            dict-type="enterWarehouseType"
          />
        </el-form-item>
        <el-form-item label="关联单据" class="clickChoose" prop="bindFormCode">
          <el-input v-model="formData.bindFormCode" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="附件" class="double">
          <FileManageFull
            :file-names="formData.fileName"
            :file-real-names="formData.fileRealName"
            :file-urls="formData.fileUrl"
            :row-index="1"
            @fileName="setFileName"
          />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            maxlength="200"
            show-word-limit
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
      </el-form>
      <div class="formItem_header">
        <div class="formItem_header_setting">入库明细<svg-icon icon-class="页面配置" @click.native="secondPageSetting" />
        </div>
        <div class="formItem_header_operate">
          <a class="formItem_header_operate_item" @click="add">
            <svg-icon icon-class="新增" />
            <div class="item_name">添加</div>
          </a>
          <a class="formItem_header_operate_item" @click="importSpareParts">
            <svg-icon icon-class="导入" />
            <div class="item_name">导入</div>
          </a>
          <a class="formItem_header_operate_item delete" @click="remove1">
            <svg-icon icon-class="删除" />
            <div class="item_name">删除</div>
          </a>
        </div>
      </div>
      <div ref="table_container2" class="table_container">
        <el-table
          ref="table"
          :data="tableDate"
          max-height="400"
          stripe
          border
          :header-cell-class-name="headerCellClassName"
          @selection-change="selectionChange1"
        >
          <el-table-column
            type="selection"
            width="50"
            align="center"
          />
          <Column
            v-for="(column,index) in tableColumns"
            :key="index"
            :prop="column.prop"
            :is-show="column.isShow"
            :label="column.label"
            :sortable="column.sortable"
            :width="column.width"
            :min-width="column.minWidth"
            :fixed="column.fixed"
            :column-type="column.columnType"
            :is-tree="column.isTree"
          />
          <el-table-column label="入库数量" fixed="right" :min-width="SETTINGS.settings_decimalDigits_length" prop="inStockNum">
            <template slot-scope="scope">
              <el-input v-model="scope.row.inStockNum" placeholder="请输入" clearable />
            </template>
          </el-table-column>
          <el-table-column label="入库仓库" fixed="right" width="150" prop="warehouseName">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.warehouseName"
                readonly
                placeholder="请选择"
                clearable
                @click.native="enterWarehouse(scope.row,scope.$index)"
              />
            </template>
          </el-table-column>
          <el-table-column label="入库库位" fixed="right" min-width="150" prop="locationName">
            <template slot-scope="scope">
              <!--              <el-input-->
              <!--                v-model="scope.row.locationName"-->
              <!--                readonly-->
              <!--                placeholder="请选择"-->
              <!--                clearable-->
              <!--                @click.native="enterWarehouseLocation(scope.row,scope.$index)"-->
              <!--              />-->
              <el-select v-model="scope.row.locationId" filterable :filter-method="getFilter" :disabled="!scope.row.warehouseName" clearable placeholder="请选择">
                <el-option
                  v-for="item in scope.row.locationOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSave">保存</el-button>
      <el-button @click.stop="onSubmit">提交</el-button>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo, importCheckout } from '@/api/warehouseManagement/elseEnterWarehouse'
import searchMaterial from '../../warehouseManagement/materialInfo/addMaterialInfo'
import moment from 'moment'
import ImportData from '@/components/JLink/common/ImportData'
import warehouseLocation from '../storageModeling/warehouseLocation'
import warehouse from '../warehouseModeling/warehouse'
import { list } from '@/api/warehouseManagement/storageModeling'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {}
  },
  data() {
    return {
      loading: true,
      formData: {
        id: undefined,
        code: undefined,
        name: undefined,
        simpleName: undefined,
        categoryCode: undefined,
        belongBysStr: undefined,
        typeId: undefined,
        model: undefined,
        purchaseTime: undefined,
        userId: undefined,
        protoId: undefined,
        protoName: undefined,
        typeName: undefined,
        realName: undefined,
        inTime: '',
        formTypeId: '',
        fileName: '',
        fileRealName: '',
        fileUrl: '',
        remark: undefined,
        status: 1,
        details: []
      },
      tableHeight: '400',
      locationId: '',
      warehouseId: '',
      pageId: '其他入库单入库明细',
      userOptions: [],
      equipmentList: [],
      selectionsAll1: [],
      selectionsAll: [], // 表格所有页选中的行
      inx: 1,
      tableDate: [],
      tableDate1: [],
      rules: {
        formTypeId: [
          { required: true, message: '入库类型不能为空', trigger: 'change' }
        ],
        formCode: [
          { required: true, message: '其他入库单号不能为空', trigger: 'blur' }
        ]
      },
      tableColumns: [], // 表格实际用的字段
      defaultTableColumns: [// 表格常规字段（初始值）
        { prop: 'materialCode', label: '物料编码', minWidth: '140' },
        { prop: 'materialName', label: '物料名称', minWidth: '140' },
        { prop: 'materialModel', label: '规格型号', minWidth: '100' },
        { prop: 'materialTypeName', label: '物料分类' },
        { prop: 'materialUnitName', label: '物料单位' },
        { prop: 'descriptionName', label: '物料属性', isShow: false },
        { prop: 'materialWeight', label: '重量', isShow: false },
        { prop: 'materialTexture', label: '材质', isShow: false },
        { prop: 'materialBrand', label: '品牌', isShow: false },
        { prop: 'palletBatchCode', label: '批号', columnType: 'input' },
        { prop: 'productDate', label: '生产日期', columnType: 'time', minWidth: '140' },
        { prop: 'remark', label: '备注', columnType: 'input', minWidth: '140' }
      ]
    }
  },
  created() {
    this.getSecondPageSetting(this, '其他入库单新增或编辑', 'tableColumns', this.defaultTableColumns)

    if (!this.id) { // 没有id就是新增
      this.formData.inByName = this.$store.state.user.name
      this.formData.inBy = this.$store.state.user.userId
      this.formData.inTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')

      this.loading = false
    } else { // 有id就是编辑
      this.getInfo()
    }
  },
  mounted() {
  },
  methods: { // 下拉框搜索要绑定的方法
    getFilter(value) {
      console.log(value, 1111)
    },
    setFileName(...data) {
      this.$set(this.formData, 'fileName', data[0])
      this.$set(this.formData, 'fileRealName', data[1])
      this.$set(this.formData, 'fileUrl', data[2])
    },
    headerCellClassName(data) {
      if (['warehouseName', 'locationName', 'inStockNum'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    selectionChange1(rows) {
      this.selectionsAll1 = rows
    },
    secondPageSetting() { // 二级页面，页面配置
      this.setSecondPageSetting('其他入库单新增或编辑', this.defaultTableColumns)
    },
    getInfo() {
      getInfo(this.id).then(res => {
        this.formData = res.data
        this.tableDate = res.data.details
        this.tableDate.filter((item, index) => {
          this.getLocationList({ warehouseId: item.warehouseId, rowIndex: index })
        })
        this.loading = false
      })
    },
    remove1() {
      this.selectionsAll1.forEach(item => {
        this.tableDate.splice(this.tableDate.indexOf(item), 1)
      })
    },
    add() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: searchMaterial, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: []
          } // props
        },
        area: ['1320px', '700px'],
        title: '选择物料', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    onSave() {
      this.$refs['form'].validate(valid => {
        let isMaterialCodeOne = true
        if (valid) {
          if (this.tableDate.filter(item => !item.inStockNum).length > 0) {
            this.$message.warning('入库数量不能为空')
            return
          } else if (this.tableDate && this.tableDate.filter(item => item.inStockNum && !this.SETTINGS.reg_no_zero.test(item.inStockNum)).length > 0) {
            this.$message.warning('入库数量未正确填写')
            return
          } else if (this.tableDate.filter(item => !item.warehouseName).length > 0) {
            this.$message.warning('入库仓库不能为空')
            return
          } else if (this.tableDate.filter(item => !item.locationId).length > 0) {
            this.$message.warning('入库库位不能为空')
            return
          }
          const tableDateOne = this.$deepClone(this.tableDate)
          this.tableDate.forEach((item, index) => {
            if (isMaterialCodeOne) {
              tableDateOne.forEach((item2, index2) => {
                if (index !== index2 && isMaterialCodeOne && item.materialId == item2.materialId && item.warehouseId == item2.warehouseId && item.locationId == item2.locationId && item.palletBatchCode == item2.palletBatchCode) {
                  isMaterialCodeOne = false
                }
              })
            }
          })
          if (isMaterialCodeOne) {
            this.formData.details = this.tableDate
            if (this.formData.details.length <= 0) {
              this.$message.warning('请添加入库明细')
              return
            }
            addOrUpdate({ ...this.formData, status: '0' }).then(res => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.$layer.close(this.layerid) // 关闭弹框
              this.$parent.refresh() // 调用父组件的刷新方法
            })
          } else {
            this.$message.warning('入库信息重复')
            return
          }
        }
      })
    },
    onSubmit() {
      let isMaterialCode = true
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.tableDate.filter(item => item.productDate > this.formData.inTime).length > 0) {
            this.$message.warning('生产日期不能晚于入库时间')
            return
          }
          if (this.tableDate.filter(item => !item.inStockNum).length > 0) {
            this.$message.warning('入库数量不能为空')
            return
          } else if (this.tableDate && this.tableDate.filter(item => item.inStockNum && !this.SETTINGS.reg_no_zero.test(item.inStockNum)).length > 0) {
            this.$message.warning('入库数量未正确填写')
            return
          } else if (this.tableDate.filter(item => !item.warehouseName).length > 0) {
            this.$message.warning('入库仓库不能为空')
            return
          } else if (this.tableDate.filter(item => !item.locationId).length > 0) {
            this.$message.warning('入库库位不能为空')
            return
          }
          const tableDateOne = this.$deepClone(this.tableDate)
          this.tableDate.forEach((item, index) => {
            if (isMaterialCode) {
              tableDateOne.forEach((item2, index2) => {
                if (index !== index2 && isMaterialCode && item.materialId == item2.materialId && item.warehouseId == item2.warehouseId && item.locationId == item2.locationId && item.palletBatchCode == item2.palletBatchCode) {
                  isMaterialCode = false
                }
              })
            }
          })
          if (isMaterialCode) {
            this.formData.details = this.tableDate
            if (this.formData.details.length <= 0) {
              this.$message.warning('请添加入库明细')
              return
            }
            addOrUpdate({ ...this.formData, status: '1' }).then(res => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.$layer.close(this.layerid) // 关闭弹框
              this.$parent.refresh() // 调用父组件的刷新方法
            })
          } else {
            this.$message.warning('入库信息重复')
            return
          }
        }
      })
    },
    // 选择仓库
    enterWarehouse(row, index) {
      this.rowIndex = index
      this.$layer.iframe({// 弹框
        content: {
          content: warehouse, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            warehouseId: row.warehouseId ? row.warehouseId : '',
            sparePartId: row.id
          }// props
        },
        area: ['880px', '570px'],
        title: '选择仓库', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    showMaterial(data) {
      data.forEach(item => {
        item.materialId = item.id
        delete item['id']
        item.remark = ''
        this.tableDate.push(item)
      })
    },
    importSpareParts() { // 导入备件物料
      this.$layer.iframe({// 弹框
        content: {
          content: ImportData, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {}// props
        },
        area: ['440px', '250px'],
        title: '导入数据', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    importMethod(files) { // 导入接口
      importCheckout(files).then(res => {
        if (res.data) {
          this.tableDate = []
          res.data.forEach((item, index) => {
            this.tableDate.push(item)
            this.getLocationList({ warehouseId: item.warehouseId, rowIndex: index, checked: false })
          })
        }
      })
    },
    // 选择仓库回调
    showWarehouse(row, checked) {
      if (this.tableDate[this.rowIndex].warehouseId !== row.id) {
        this.tableDate[this.rowIndex].locationName = ''
        this.tableDate[this.rowIndex].locationId = ''
      }
      if (checked == false) { // 没有默认其他物料也加入该仓库
        const arr = this.$deepClone(this.tableDate)
        arr[this.rowIndex].warehouseId = row.id
        arr[this.rowIndex].warehouseName = row.name
        this.warehouseId = row.id
        this.tableDate = arr
      } else { // 默认其他物料也加入该仓库
        const arr = this.$deepClone(this.tableDate)
        arr.forEach((item, index) => {
          item.warehouseId = row.id
          item.warehouseName = row.name
          this.warehouseId = row.id
          if (item.warehouseId == row.id) {
            item.locationName = ''
            item.locationId = ''
          }
        })
        this.tableDate = arr
      }
      this.getLocationList({ warehouseId: this.warehouseId, rowIndex: this.rowIndex, checked: checked })
    },
    getLocationList(row) { // 仓库回调触发的方法，用来根据仓库id获取库位
      list({ pageNum: 1, pageSize: 9999, status: 1, warehouseId: row.warehouseId }).then(res => {
        if (row.checked == false) {
          const arr = this.$deepClone(this.tableDate)
          arr[row.rowIndex].locationOptions = []
          res.data.filter(item => {
            if (arr[row.rowIndex].warehouseId == item.warehouseId) {
              if (res.data.length == 1) {
                arr[row.rowIndex].locationName = item.locationName
                arr[row.rowIndex].locationId = item.id
              }
              arr[row.rowIndex].locationOptions.push({
                value: item.id,
                label: item.locationName
              })
            }
          })
          this.tableDate = arr
        } else {
          const arr = this.$deepClone(this.tableDate)
          arr.filter(item => {
            item.locationOptions = []
            res.data.filter(ele => {
              if (item.warehouseId == ele.warehouseId) {
                if (res.data.length == 1) {
                  item.locationName = ele.locationName
                  item.locationId = ele.id
                }
                item.locationOptions.push({
                  value: ele.id,
                  label: ele.locationName
                })
              }
            })
          })
          this.tableDate = arr
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.formItem_header_setting{
  svg{
    margin-left: 10px;
    font-size: 14px;
    color: #387bfc;
    cursor: pointer;
  }
}
</style>
